package com.supermarket.api.service.impl;

import com.supermarket.api.common.Constants;
import com.supermarket.api.entity.CategoryEntity;
import com.supermarket.api.entity.SelectedCategoryEntity;
import com.supermarket.api.repository.CategoryRepository;
import com.supermarket.api.repository.SelectedCategoryRepository;
import com.supermarket.api.service.SelectedCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 精选分类服务层
 * @author 李其伟
 * @date 2023/10/23
 */
@Slf4j
@Service
public class SelectedCategoryServiceImpl implements SelectedCategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private SelectedCategoryRepository selectedCategoryRepository;

    @Override
    public List<CategoryEntity> list() {
        List<SelectedCategoryEntity> selectedCategoryEntityList = selectedCategoryRepository.findAllByPublishStatusOrderBySortDesc(Constants.PUBLISH_STATUS_UP);
        List<Long> ids = selectedCategoryEntityList.stream().map(SelectedCategoryEntity::getCategoryId).collect(Collectors.toList());
        List<CategoryEntity> list = categoryRepository.findAllByPublishStatusAndIdIn(Constants.PUBLISH_STATUS_UP,ids);

        Map<Long,CategoryEntity> categoryMap = list.stream().collect(Collectors.toMap(CategoryEntity::getId, ce->ce));

        return ids.stream().map(id-> categoryMap.get(id)).collect(Collectors.toList());
    }
}
